package com.swlz.servlet.admin;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.swlz.R;
import com.swlz.config.AlipayConfig;
import com.swlz.config.GoFastDfsConfig;
import com.swlz.config.SystemConfig;
import com.swlz.entity.Config;
import com.swlz.service.ConfigService;
import com.swlz.service.impl.ConfigServiceImpl;
import com.swlz.servlet.HttpServletSupport;

import cn.hutool.extra.servlet.ServletUtil;

/**
 * <pre>
 * - JSON控制器
 * - 系统配置
 * ClassName : com.swlz.servlet.demo.ConfigServlet
 * Author :swlz
 * E-Mail : 2233875735@qq.com
 * Date : 2020-07-02 18:41:53
 * Version : 1.0
 * Copyright 2020 swlz.top Inc. All rights reserved. 
 * Warning: this content is only for internal circulation of the company. It is forbidden to divulge it or use it for other commercial purposes
 * </pre>
 **/
@SuppressWarnings("serial")
@WebServlet("/admin/config.let")
public class ConfigServlet extends HttpServletSupport {
	
	private ConfigService configService = new ConfigServiceImpl();
	
	public R<?> update(HttpServletRequest request)throws Exception {
		String configKey = "com.swlz.config."+request.getParameter("configKey");
		Config config = new Config();
		config.setConfigKey(configKey);
		Class<?> cls = Class.forName(configKey);
		if(cls==SystemConfig.class){
			ServletUtil.fillBean(request, configService.getSystemConfig(), true);
			config.setConfigValue(JSON.toJSONString(configService.getSystemConfig()));
		}else if(cls == AlipayConfig.class){
			ServletUtil.fillBean(request, configService.getAlipayConfig(), true);
			config.setConfigValue(JSON.toJSONString(configService.getAlipayConfig()));
		}else if(cls == GoFastDfsConfig.class){
			ServletUtil.fillBean(request, configService.getGoFastDfsConfig(), true);
			config.setConfigValue(JSON.toJSONString(configService.getGoFastDfsConfig()));
		}
		try{
			configService.add(config);
		}catch(Exception ex){
			configService.update(config);
		}
		return R.ok("修改系统配置成功");
	}

	
	public void get(Config config,HttpServletResponse response)throws Exception {
		response.setContentType("text/json;charset=UTF-8");
		try{
			response.getWriter().print(configService.get("com.swlz.config."+config.getConfigKey()).getConfigValue());
		}catch(Exception ex){
			response.getWriter().print(JSON.toJSONString(Class.forName("com.swlz.config."+config.getConfigKey()).newInstance()));
		}
		response.flushBuffer();
	}
	
	
}